import axios from 'axios';
import { Loading, Message } from 'element-ui';
import router from '../router'
let loading;

// 开始加载
function startLoading() {
  loading = Loading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.3)',
    fullscreen: true
  });
}

// 结束加载
function endLoading() {
  loading.close();
}

// 请求拦截
axios.interceptors.request.use(config => {
  startLoading();
  // 每次发起请求时，如果本地存储有 moneyToken，则作为头部信息一起发送
  if (localStorage.moneyToken) {
    config.headers.Authorization = localStorage.moneyToken;
  }
  return config;
}, error => {
  return Promise.reject(error);
})

// 响应拦截
axios.interceptors.response.use(response => {
  endLoading();
  return response;
}, error => {
  endLoading();
  // 响应出错时拿到状态码，如果是401，则表示Token失效
  let { status } = error.response;
  if (status == 401) {
    Message.error('Token失效，请重新登录');
    localStorage.removeItem('moneyToken');
    router.replace({ name: 'Login' });
  }
  return Promise.reject(error);
})


axios.defaults.baseURL = "http://localhost:3000/api";

export default axios;